package com.fxwater.api.auth;

import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.alibaba.fastjson.JSONObject;
import com.fxwater.api.ApiConst;
import com.fxwater.common.core.domain.AjaxResult;
import com.fxwater.system.domain.SysUser;
import com.fxwater.system.service.ISysUserService;

/**
 * 
 * 自定义拦截器，判断此次请求是否有权限
 *
 * @author: tzh
 * @date: 2018年10月18日 下午12:24:18
 *
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
	Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ISysUserService userService;

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();

        // 验证方法注明了Authorization,则验证用户token
        if (method.getAnnotation(Authorization.class) != null) {
            // 从header中得到token
            String userToken = request.getHeader(ApiConst.TOKEN_KEY);
            // 验证token
            logger.debug("{}: {}", ApiConst.TOKEN_KEY, userToken);
            SysUser user = userService.getByToken(userToken);
            if (user != null) {
                request.getSession().setAttribute(ApiConst.LOGIN_SESSION_KEY, user);
                return true;
            } else {
                // 如果验证token失败，并且方法注明了Authorization，返回401错误
                logger.info("验证用户身份失败-------------userToken: {}", userToken);
                AjaxResult ajaxResult = new AjaxResult(AjaxResult.Type.UNAUTHORIZED, "请登录");
                response.setContentType("application/json;charset=UTF-8");
                response.setCharacterEncoding("utf-8");
                response.getWriter().println(JSONObject.toJSONString(ajaxResult));
                return false;
            }
        }
        return true;
	}
}
